<?php


namespace App\Extensions\Column;


use Encore\Admin\Grid\Column\InputFilter;
use Encore\Admin\Grid\Model;

class InputRelationFilter extends InputFilter
{
    /**
     * @var string
     */
    protected $type;
    /**
     * @var
     */
    protected $relation;
    /**
     * @var
     */
    protected $column;

    /**
     * InputFilter constructor.
     *
     * @param string $type
     */

    public function __construct($type, $relation, $column='')
    {
        $this->relation = $relation;
        $this->column = $column;
        parent::__construct($type);
    }

    /**
     * 修正Grid 关联无法获取request值 如；
     * @return array|mixed|string|string[]
     */
    public function getColumnName()
    {
        return str_replace('.', '_', $this->parent->getName());
    }
    /**
     * Add a binding to the query.
     *
     * @param string     $value
     * @param Model|null $model
     */
    public function addBinding($value, Model $model)
    {
        $value = $value?:$this->getFilterValue();
        if (empty($value)) {
            return;
        }
        if ($this->relation instanceof \Closure) {
            $callback = $this->relation->bindTo($model);
            call_user_func_array($callback, [$model,$value]);
        } else {
            $model->whereHas($this->relation,function($model)use($value){
                if ($this->type == 'like') {
                    $model->where($this->column, 'like', "%{$value}%");
                }elseif (in_array($this->type, ['date', 'time'])) {
                    $method = 'where'.ucfirst($this->type);
                    $model->{$method}($this->column, $value);
                }else{
                    $model->where($this->column, $value);
                }
            });
        }
    }

}
